import java.sql.DriverManager

import code.schema.DB
import code.schema.SquerylEntrypoint._
import org.squeryl.adapters.H2Adapter
import org.squeryl.{Session, SessionFactory}

object Main {
  def main(args: Array[String]): Unit = {
    init4H2()

    inTransaction {
      val students0 = from(DB.students)(s => select((s.departmentId, s.name)))
      val r0 = join(students0, DB.departments.leftOuter)((s, d) => select((s, d)) on (d.map(_.id) === s._1))
      println(r0.statement) //generate error messages as expected.

      //Be more complicated than students0
      val students = from(DB.students)(s => where(1 === 1) select s orderBy (s.departmentId desc)).page(0, 10)
      val r = join(students, DB.departments.leftOuter)((s, d) => select((s, d)) on (d.map(_.id) === s.departmentId))
      println(r.statement) //OK
    }
  }

  def init4H2(): Unit = {
    Class.forName("org.h2.Driver")
    SessionFactory.concreteFactory = Some(() =>
      Session.create(
        DriverManager.getConnection("jdbc:h2:mem:db1;DB_CLOSE_DELAY=-1", "sa", ""),
        new H2Adapter))
  }
}

